package com.itbour.common.base;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.google.gson.Gson;
import com.itbour.dto.yjx.user.Result;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

/**
 * copyright   pirate alliance team 2014
 * @author     xuwei
 */
public class BaseAction extends ActionSupport implements Preparable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	protected HttpServletRequest request;
	protected HttpServletResponse response;
	protected Map<String, Object> session;

    /* (non-Javadoc)
     * @see com.opensymphony.xwork2.Preparable#prepare()
     */
    public void prepare() throws Exception
    {
        // TODO Auto-generated method stub

    }
    
    /**
	 * 将字符串写入到response
	 * 
	 * @param text
	 * @throws Exception
	 */
	protected void writeText(String text) throws Exception {
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().write(text);
	}
	
	/**
	 * 将JSON对象写入到response
	 * 
	 * @param jsonObject
	 * @throws Exception
	 */
	protected void writeJSON(Object jsonObject) throws Exception {
		Gson gson = new Gson();
		String result = gson.toJson(jsonObject);
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().write(result);
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	public Map<String, Object> getSession() {
		return session;
	}

	public void setSession(Map<String, Object> session) {
		this.session = session;
	}
	
	// 控制器单例
	protected Logger log = Logger.getLogger(getClass());
	
	
	
	// 请求错误
	public Object renderError(String msg){
		Result res = new Result();
		res.setMsg(msg);
		res.setSuccess(0);
		return res;
	}
	
	// 请求成功
	public Object renderSucc(String msg){
		Result res = new Result();
		res.setMsg(msg);
		res.setSuccess(1);
		return res;
	}
	
	// 请求成功 返回成功
	public Object renderSucc(String msg,Object obj){
		Result res = new Result();
		res.setMsg(msg);
		res.setSuccess(1);
		res.setData(obj);
		return res;
	}

}
